# app/__init__.py
from flask import Flask
from flask_login import LoginManager
from flasgger import Swagger
from app.extensions import db
from app.models.user import User
from app.models.movie import Movie
from app.models.favorite import Favorite

def create_app():
    app = Flask(__name__)
    app.secret_key = 'your_secret_key_here'

    app.config['SWAGGER'] = {
        'title': '电影收藏系统 API',
        'uiversion': 3
    }
    Swagger(app)

    # ⚠️ 自动重建表
    if db.is_closed():
        db.connect()
    db.drop_tables([User, Movie, Favorite])
    db.create_tables([User, Movie, Favorite])



    # 登录管理
    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(user_id):
        return User.get_or_none(User.id == int(user_id))

    # 注册蓝图
    from app.routes.auth_routes import auth_bp
    from app.routes.movie_routes import movie_bp
    from app.routes.favorite_routes import favorite_bp

    app.register_blueprint(auth_bp)
    app.register_blueprint(movie_bp)
    app.register_blueprint(favorite_bp)

    return app
